package es.ceura.wilder.handlers;

import es.ceura.wilder.configuration.Config;
import es.ceura.wilder.logger.Logger;
import es.ceura.wilder.datastructures.Message;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 *
 * @author Jorge Madrid
 */
public class MessageReciever {

    private InputStream input;
    private static final String EOH = "\r\n";

    public MessageReciever() {
    }

    public String recieveHTTPData(Socket clientSocket) {
        StringBuilder builder = null;
        try {
            input = clientSocket.getInputStream();
            builder = new StringBuilder();
            String line;
            while (!EOH.equals(line = readLine())) {
                builder.append(line);
            }
        } catch (IOException ex) {
            Logger.INSTANCE.logError("Error al copiar bytes desde input de socket: " + clientSocket, ex);
        }
        return builder == null ? "" : builder.toString();
    }

    private String readLine() throws IOException {
        int character;
        StringBuilder builder = new StringBuilder();
        while ((character = input.read()) != 10) {
            builder.append((char) character);
        }
        builder.append("\n");
        return builder.toString();
    }

    public Message recieveMessage(Socket clientSocket, int size) throws IOException {
        Message message = null;
        try {
            int bufferSize = Integer.parseInt(Config.INSTANCE.getConfigVar(Config.BUFFER_SIZE));
            int read, totalRead = 0;
            byte[] buffer = new byte[bufferSize];

            message = new Message(size);

            while (totalRead < size) {
                read = input.read(buffer);
                message.appendData(buffer, read);
                totalRead += read;
            }

        } catch (IOException ex) {
            Logger.INSTANCE.logError("Error al copiar bytes desde input de socket: " + clientSocket, ex);
        }
        return message != null ? message : new Message(0);
    }
}
